from datetime import datetime
from app import db
from app.models import AIStyle

class AIStyleService:
    @staticmethod
    def create_ai_style(user_id, name, prompt, description=None):
        # 检查是否已存在相同用户和名称的AI风格
        existing = AIStyle.query.filter_by(uid=user_id, name=name).first()
        if existing:
            raise ValueError(f"AI style with name '{name}' already exists for this user")
            
        ai_style = AIStyle(
            uid=user_id,
            name=name,
            prompt=prompt,
            description=description
        )
        db.session.add(ai_style)
        db.session.commit()
        return ai_style

    @staticmethod
    def get_user_ai_styles(user_id):
        return AIStyle.query.filter_by(uid=user_id).all()

    @staticmethod
    def get_ai_style(user_id, style_id):
        return AIStyle.query.filter_by(id=style_id, uid=user_id).first()

    @staticmethod
    def update_ai_style(ai_style, name=None, prompt=None, description=None):
        if name is not None:
            ai_style.name = name
        if prompt is not None:
            ai_style.prompt = prompt
        if description is not None:
            ai_style.description = description
        db.session.commit()
        return ai_style

    @staticmethod
    def delete_ai_style(ai_style):
        db.session.delete(ai_style)
        db.session.commit()
